<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex items-center justify-between">
        <h1 class="text-xl font-semibold text-gray-900">今天我们要使用哪个知识库？</h1>
        <div class="flex items-center gap-4">  <!-- 关键：使用 gap-4 控制间距 -->
          <!-- 搜索框部分 -->
          <div class="flex items-center flex-1">
            <i class="fas fa-search text-gray-400 mr-2" @click="handleSearch"></i>

            <el-input
              v-model="searchText"
              placeholder="请输入知识库名称"
              @keyup.enter="handleSearch"
              @blur="handleSearch"
              clearable /><!-- 添加可清空功能 -->
          </div>

          <!-- 创建按钮 -->
          <el-button
            class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded h-[40px] whitespace-nowrap"
            @click="openCreateModal"
          >
            <i class="fas fa-plus mr-2"></i>创建知识库
          </el-button>
        </div>
      </div>
    </header>

    <!-- 主要内容区 -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
        <div v-for="(category, index) in categories" :key="index" class="bg-white rounded-lg shadow-md overflow-hidden">
          <div class="p-6">
            <div class="flex items-center justify-between mb-4">

              <h2 class="text-xl font-semibold text-gray-900">
                <router-link :to="{ path: '/rag/data', query: {datasetId:category.id } }">
                  {{ category.name }}
                </router-link>
              </h2>

              <div class="relative">
                <el-button
                  class="text-gray-500 hover:text-gray-700"
                  size="mini"
                @click="toggleMenu(index)"
                >

                <i class="fas fa-ellipsis-h"></i>
                </el-button>
                <div v-if="category.showMenu" class="absolute right-0 mt-2 w-48 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5">
                  <div class="py-1" role="menu" aria-orientation="vertical" aria-labelledby="options-menu">
                    <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem" @click="editCategory(category)">编辑</a>
                    <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem" @click="deleteCategory(category)">删除</a>
                  </div>
                </div>
              </div>
            </div>
            <div class="flex items-center text-sm text-gray-500 mb-2">
              <i class="far fa-file-alt mr-2"></i>
              <span>{{ category.document_count }} 文档</span>
            </div>
            <div class="flex items-center text-sm text-gray-500">
              <i class="far fa-clock mr-2"></i>
              <span>{{ formatDateTime(category.update_date)}}</span>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部信息 -->
    <footer class="bg-white border-t border-gray-200 mt-8">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 text-center text-sm text-gray-500">
        <p>当前共有 {{ categories.length }} 个知识库分类</p>
        <p class="mt-2">知识就是力量，继续加油！</p>
      </div>
    </footer>

    <!-- 创建知识库的模态框 -->
    <!-- 创建/编辑知识库的模态框 -->
    <div v-if="showCreateModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
      <div class="bg-white rounded-lg shadow-lg w-1/3">
        <div class="p-6">
          <h2 class="text-xl font-semibold mb-4">{{ isEditMode ? '编辑知识库' : '创建知识库' }}</h2>
          <form>
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700">名称</label>
              <el-input v-model="newKnowledgeBase.name" type="text" />
            </div>
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700">描述</label>
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入描述"
                v-model="newKnowledgeBase.description">
              </el-input>

<!--              <textarea v-model="newKnowledgeBase.description"  class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></textarea>-->
            </div>
<!--            <div class="mb-4">-->
<!--              <label class="block text-sm font-medium text-gray-700">头像 URL</label>-->
<!--              <input v-model="newKnowledgeBase.avatar" type="text" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">-->
<!--            </div>-->
<!--            <div class="mb-4">-->
<!--              <label class="block text-sm font-medium text-gray-700">嵌入模型</label>-->
<!--              <input v-model="newKnowledgeBase.embedding_model" type="text"  class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">-->
<!--            </div>-->
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700">权限</label>
              <el-select v-model="newKnowledgeBase.permission" style="width:100%">
                <el-option value="me" label="仅自己"></el-option>
                <el-option value="team" label="团队"></el-option>
              </el-select>
            </div>
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700">分块方法</label>
              <el-select v-model="newKnowledgeBase.chunk_method" style="width:100%">
                <el-option value="naive" label="General"></el-option>
                <el-option value="qa" label="Q&A"></el-option>
                <el-option value="manual" label="Manual"></el-option>
                <el-option value="table" label="Table"></el-option>
                <el-option value="paper" label="Paper"></el-option>
                <el-option value="book" label="Book"></el-option>
                <el-option value="laws" label="Laws"></el-option>
              </el-select>
<!--              <input v-model="newKnowledgeBase.chunk_method" type="text" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">-->
            </div>
<!--            <div class="mb-4">-->
<!--              <label class="block text-sm font-medium text-gray-700">解析配置</label>-->
<!--              <textarea v-model="newKnowledgeBase.parser_config" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></textarea>-->
<!--            </div>-->
            <div class="flex justify-end">
              <el-button type="info"  @click="closeCreateModal">取消</el-button>
              <el-button type="primary" >
                <span v-if="isEditMode" @click="updateKnowledgeBase">
                  更新
                </span>
                <span v-else @click="createKnowledgeBase">
                  创建
                </span>

              </el-button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {dataList, createDataset, deleteDataset, delFile, updateDataset,search} from "../../api/rag/rag"; // 假设你已经有一个 createDataset 的 API 方法

export default {
  data() {
    return {
      username: 'yyy',
      categories: [],
      isEditMode:false,
      showCreateModal: false,
      newKnowledgeBase: {
        name: '',
        description: '',
        avatar: '',
        embedding_model: '',
        permission: '',
        chunk_method: '',
        parser_config: '{}',

      },
      searchText: '',
      newName: ''
    };
  },

  mounted() {

    this.getList();
  },

  methods: {
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '无日期信息';

      // 如果 dateTimeStr 不带时区（如 "2023-05-15T14:30:00"），手动加上 +08:00
      const beijingTimeStr = dateTimeStr.endsWith('Z')
        ? dateTimeStr.replace('Z', '+08:00')  // 如果原本是 UTC (Z)，改为 +08:00
        : dateTimeStr.includes('+')
          ? dateTimeStr  // 如果已经有时区，不做处理
          : `${dateTimeStr}+08:00`;  // 否则加上 +08:00

      const date = new Date(beijingTimeStr);
      if (isNaN(date.getTime())) return '无效日期';
      const options = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' };
      return new Intl.DateTimeFormat('zh-CN', options).format(date);
    },

    getList() {
      dataList(1, 10,'').then((res) => {
        this.categories = res.data;
      });
    },

    handleSearch() {
      // 调用API进行搜索
      search(1, 10, this.searchText).then((res) => {
        this.categories = res.data;
      }).catch(error => {
        console.error('搜索失败:', error);
        this.$message.error('搜索失败');
      });
    },

    openCreateModal() {
      this.isEditMode = false; // 设置为创建模式
      this.showCreateModal = true;
    },

    openEditModal(category) {
      console.log('编辑按钮点击，当前分类:', category);
      this.isEditMode = true;
      this.currentCategoryId = category.id;
      this.newKnowledgeBase = {
        name: category.name,
        description: category.description,
        avatar: category.avatar,
        embedding_model: category.embedding_model,
        permission: category.permission,
        chunk_method: category.chunk_method,
        parser_config: JSON.stringify(category.parser_config || {})
      };
      console.log('填充的表单数据:', this.newKnowledgeBase);
      this.showCreateModal = true;
    },

    closeCreateModal() {
      this.showCreateModal = false;
      this.newKnowledgeBase = {
        name: '',
        description: '',
        avatar: '',
        embedding_model: '',
        permission: '',
        chunk_method: '',
        parser_config: '{}'
      }; // 重置表单
    },

    createKnowledgeBase() {
      const payload = {
        name: this.newKnowledgeBase.name,
        description: this.newKnowledgeBase.description,
        // avatar: this.newKnowledgeBase.avatar,
        // embedding_model: this.newKnowledgeBase.embedding_model,
        permission: this.newKnowledgeBase.permission,
        chunk_method: this.newKnowledgeBase.chunk_method,
        // parser_config: JSON.parse(this.newKnowledgeBase.parser_config || '{}')
      };



      createDataset(payload).then((res) => {
        console.log(12,res);
        this.getList(); // 重新获取列表
        this.closeCreateModal();

        this.$message({message:'创建成功',type:'success'})

        // if (res.success) {
        //
        // } else {
        //   alert('创建失败，请重试');
        // }
      }).catch((error) => {
        console.error(error);
        this.$message({message:'创建失败，请重试',type:'error'})

      });
    },

    updateKnowledgeBase() {
      const payload = {
        name: this.newKnowledgeBase.name,
        description: this.newKnowledgeBase.description,
        // avatar: this.newKnowledgeBase.avatar,
        // embedding_model: this.newKnowledgeBase.embedding_model,
        permission: this.newKnowledgeBase.permission,
        chunk_method: this.newKnowledgeBase.chunk_method,
        // parser_config: JSON.parse(this.newKnowledgeBase.parser_config || '{}')
      };

      console.log(13,this.newKnowledgeBase.id)

      updateDataset(this.newKnowledgeBase.id, payload).then((res) => {
        this.getList(); // 重新获取列表
        this.closeCreateModal();
        this.$message({message:'编辑成功',type:'success'})
      }).catch((error) => {
        this.$message({message:'编辑失败',type:'success'})
      });
    },

      toggleMenu(index) {
      this.categories = this.categories.map((category, i) => {
        if (i === index) {
          return { ...category, showMenu: !category.showMenu };
        }
        return { ...category, showMenu: false };
      });
    },

    editCategory(category) {
      console.log(category)
      this.showCreateModal = true;
      dataList(1,1,category.id).then((res) => {
        this.isEditMode=true
        console.log(11,res)
        this.newKnowledgeBase=res.data[0]
        console.log(12,this.newKnowledgeBase)
      })

    },


    async deleteCategory(category) {

      this.$msgbox({
        title: '删除确认',
        message: '确认删除吗？',
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }).then(action => {
        if (action === "confirm") {
          deleteDataset([category.id]).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getList();
          })
        }

        // if (confirm(`确定要删除 "${category.name}" 分类吗？`)) {
        //   try {
        //     await deleteDataset([category.id]).then((res)=>{
        //       this.categories = this.categories.filter(c => c !== category); // 更新前端列表
        //       this.$message({message:'删除成功',type:'success'})
        //
        //     }).catch((error) => {
        //       console.error(error);
        //       this.$message({message:'删除失败',type:'error'})
        //
        //     });


        // const response = await deleteDataset([category.id]); // 调用 deleteDataset 方法
        // if (response.success) {
        //   this.categories = this.categories.filter(c => c !== category); // 更新前端列表
        //   alert('删除成功！');
        // } else {
        //   alert('删除失败：' + response.message);
        // }
        // } catch (error) {
        //   console.error('请求失败:', error);
        //   alert('请求失败，请检查网络或稍后重试。');
//         }
//       }
      })
    }
  }
};
</script>

<style scoped>
/* 移除 input[type="number"] 的默认箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
input[type="number"] {
  -moz-appearance: textfield;
}
</style>
